const seturl = "http://localhost:8000";

let urlString = window.location.href.split('?');
let id = urlString[urlString.length - 1] * 1;
if (id) {
    fetch(`${seturl}/User/${id}`, {
        method: "GET"
    }).then(res => {
        // console.log(res);

        return res.json()
    }).then(data => {
        console.log(data.data);
        const udata = data.data
        // registrationTime
        let newtime = getBeiJiTime()
        udata.registrationTime = newtime;

        // console.log(formGroup[0]);
        let formGroup = document.querySelectorAll('.form-group')
        let newdata = []
        formGroup.forEach(element => {
            newdata.push(element.lastElementChild)
        });

        newdata.forEach((inputElement) => {
            // 如果对象中有与当前input名称相同的键名，则更新该input的value
            if (udata.hasOwnProperty(inputElement.name)) {
                inputElement.value = udata[inputElement.name];

            }
        });
    })


}

document.querySelector("form").addEventListener("submit", (e) => {
    // 阻止默认行为
    e.preventDefault();
    let formGroup = document.querySelectorAll('.form-group');
    // console.log(formGroup[0]);


    let userObj = {};
    formGroup.forEach((item) => {
        console.log(item);

        userObj[item.lastElementChild.id] = item.lastElementChild.value
    })

    console.log(userObj);

    if (!id) {
        // Add
        fetch(`${seturl}/User`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify(userObj),
        }).then((response) => response.json())
            .then((userObj) => {
                console.log("Success:", userObj);
                location.href = "./Users.html"
            })
            .catch((error) => {
                console.error("Error:", error);
            });

    } else {

        //Update
        fetch(`${seturl}/User/${id}`, {
            method: "PUT",
            headers: {
                "Content-Type": "application/json",

            },
            body: JSON.stringify(userObj)
        }).then((response) => response.json())
            .then((userObj) => {
                console.log("Success:", userObj);
                location.href = "./Users.html"
            })
            .catch((error) => {
                console.error("Error:", error);
            });

        // document.addEventListener("DOMContentLoaded", function () {

        //     let registratioName = document.querySelector("#name");
        //     let registrationAge = document.querySelector("#age");
        //     let registrationEmail = document.querySelector("#email");
        //     let registrationGender = document.querySelector("#gender");

        //     registratioName.value = user


        // });
    }
})


// RegistrationTimeInput
window.addEventListener("DOMContentLoaded", () => {
    let registrationTimeInput = document.querySelector("#registrationTime");
    let newtime = getBeiJiTime()
    registrationTimeInput.value = newtime;
}
);

function getBeiJiTime() {
    let now = new Date();

    const utcDate = new Date(now.toISOString());
    const beijingTime = new Date(utcDate.getTime() + 8 * 60 * 60 * 1000);   // 加 8 小时

    // console.log(beijingTime.toISOString().slice(0, 16).replace('T', ' '));
    return newtime = beijingTime.toISOString().slice(0, 16).replace('T', ' ');
    // console.log(now.toISOString().slice(0, 16));
    // console.log(now.toLocaleString());

}